<template>
    <div>
        <div class="dz-title">VUE打印测试</div>
        <ul class="dz-opt-group">
            <div class="dz-opt-item">
                <label class="dz-opt-item-title">打印机:</label
                ><select class="dz-opt-item-value" v-model="currPrinter" @change="onPrinterChanged">
                    <option v-for="item in printers" :key="item.title" :value="item.value">{{ item.name }}</option>
                </select>
            </div>
            <div class="dz-opt-item">
                <label class="dz-opt-item-title">纸张类型:</label
                ><select class="dz-opt-item-value" v-model="currGapType">
                    <option v-for="item in gapTypes" :key="item.value" :value="item.value">{{ item.name }}</option>
                </select>
            </div>
            <div class="dz-opt-item">
                <label class="dz-opt-item-title">打印浓度:</label
                ><select class="dz-opt-item-value" v-model="currDarkness">
                    <option v-for="item in darkness" :key="item.value" :value="item.value">{{ item.name }}</option>
                </select>
            </div>
            <div class="dz-opt-item">
                <label class="dz-opt-item-title">打印速度:</label
                ><select class="dz-opt-item-value" v-model="currSpeed">
                    <option v-for="item in speeds" :key="item.value" :value="item.value">{{ item.name }}</option>
                </select>
            </div>
            <div class="dz-opt-item">
                <label class="dz-opt-item-title">打印方向:</label
                ><select class="dz-opt-item-value" v-model="currOrientation">
                    <option v-for="item in orientations" :key="item.value" :value="item.value">{{ item.name }}</option>
                </select>
            </div>
            <div class="dz-opt-item">
                <label class="dz-opt-item-title">打印模式:</label
                ><select class="dz-opt-item-value" v-model="currAction">
                    <option v-for="item in jobTypes" :key="item.value" :value="item.value">{{ item.name }}</option>
                </select>
            </div>
            <div class="dz-opt-item" v-show="currAction === 0x01">
                <label class="dz-opt-item-title">打印机精度:</label
                ><select class="dz-opt-item-value" v-model="printerDPI">
                    <option v-for="item in printerDpiList" :key="item.value" :value="item.value">
                        {{ item.name }}
                    </option>
                </select>
            </div>
            <div class="dz-opt-item" v-show="currAction === 0x01">
                <label class="dz-opt-item-title">打印头宽度:</label
                ><input class="dz-opt-item-value" type="number" v-model="printerWidth" />
            </div>
        </ul>
        <fieldset>
            <legend>打印机相关</legend>
            <ul class="dz-btn-group">
                <a class="button" @click="onOpenPrinter()">打开打印机</a>
                <a class="button" @click="onClosePrinter()">关闭打印机</a>
                <a class="button" @click="onGetPrinterName()">获取打印机名称</a>
                <a class="button" @click="onIsPrinterOpened()">打印机是否打开</a>
                <a class="button" @click="onShowPrinterProperty()">显示打印机属性</a>
            </ul>
        </fieldset>
        <fieldset>
            <legend>任务绘制测试</legend>
            <ul class="dz-btn-group">
                <a class="button" @click="onDrawText()">绘制文本</a>
            </ul>
            <ul class="dz-btn-group">
                <a class="button" @click="onSetAlign()">对齐方式测试</a>
                <a class="button" @click="onSetRotation()">内容旋转测试</a>
            </ul>
            <ul class="dz-btn-group">
                <a class="button" @click="onDrawBarcode()">绘制一维码</a>
                <a class="button" @click="onDrawQrcode()">绘制二维码</a>
                <a class="button" @click="onDrawPDF417()">绘制PDF417</a>
                <a class="button" @click="onDrawDataMatrix()">绘制DataMatrix</a>
            </ul>
            <ul class="dz-btn-group">
                <a class="button" @click="onDrawImageFile()">绘制url图片</a>
                <a class="button" @click="onDrawImageData()">绘制BASE64图片</a>
            </ul>
            <ul class="dz-btn-group">
                <a class="button" @click="onDrawLine()">绘制直线</a>
                <a class="button" @click="onDrawRect()">绘制矩形</a>
                <a class="button" @click="onDrawEllipse()">绘制椭圆</a>
                <a class="button" @click="onDrawCircle()">绘制圆形</a>
            </ul>
        </fieldset>
        <fieldset>
            <legend>打印测试</legend>
            <ul class="dz-btn-group">
                <a class="button" @click="onTablePrintTest()">表格打印测试</a>
                <a class="button" @click="onJsonPrintTest()">JSON数据打印测试</a>
                <a class="button" @click="onWdfxPrintTest()">WDFX文件打印测试</a>
                <a class="button" @click="onPrintImageData()">打印BASE64(预览)图片</a>
                <a class="button" @click="onPrintRawData()">RawData打印测试</a>
            </ul>
        </fieldset>
        <div ref="preview-group" @dragenter="onFileDragEnter" @dragover="onFileDragEnter" @drop="onFileDragDrop">
            <fieldset class="dz-preview-group">
                <legend>打印预览</legend>
                <div class="dz-preview" ref="preview-list"></div>
            </fieldset>
        </div>
        <div style="display: none">
            <input id="file-picker" type="file" :accept="pickerAccept" />
        </div>
    </div>
</template>

<script>
import { DTPWeb, LPA_PrintActions } from "dtpweb";

export default {
    name: "App",
    data() {
        return {
            printers: [{ name: "未检测到打印机", value: {} }],
            currPrinter: { name: "" },
            gapTypes: [
                { name: "随打印机", value: 255 },
                { name: "连续纸", value: 0 },
                { name: "定位孔", value: 1 },
                { name: "间隙纸", value: 2 },
            ],
            currGapType: 255,
            speeds: [
                { name: "随打印机", value: 255 },
                { name: "1(特慢)", value: 0 },
                { name: "2(慢)", value: 1 },
                { name: "3(正常)", value: 2 },
                { name: "4(快)", value: 3 },
                { name: "5(特快)", value: 4 },
            ],
            currSpeed: 255,
            darkness: [
                { name: "随打印机", value: 255 },
                { name: "6(正常)", value: 5 },
                { name: "7", value: 6 },
                { name: "8", value: 7 },
                { name: "9", value: 8 },
                { name: "10(较浓)", value: 9 },
                { name: "11", value: 10 },
                { name: "12", value: 11 },
                { name: "13", value: 12 },
                { name: "14", value: 13 },
                { name: "15(特浓)", value: 14 },
            ],
            currDarkness: 255,
            jobTypes: [
                { name: "打印模式", value: LPA_PrintActions.Print },
                { name: "白色底色图片", value: LPA_PrintActions.PrevBase64 },
                { name: "透明底色图片", value: LPA_PrintActions.TransBase64 },
                { name: "生成打印数据", value: LPA_PrintActions.PrintData },
            ],
            currAction: LPA_PrintActions.PrevBase64,
            orientations: [
                { name: "水平方向", value: 0 },
                { name: "右转90度", value: 90 },
                { name: "180度旋转", value: 180 },
                { name: "左转90度", value: 270 },
            ],
            currOrientation: 0,
            printerDpiList: [
                { name: "200点", value: 203 },
                { name: "300点", value: 300 },
            ],
            printerDPI: 203,
            printerWidth: 384,
            /**
             * @type {DTPWeb | undefined}
             */
            api: undefined,
            showDocument: false,
            jobName: "",
            wdfxContent: "",
            pickerAccept: "",
            /**
             * @type {string[][]}
             */
            printData: [],
        };
    },
    mounted() {
        DTPWeb.checkServer({
            // jsonMode: false,
            downloadUrl: "https://weida.dothantech.com/beta/assets/dtpweb/index.html",
            callback: (api, server) => {
                this.api = api;
                console.log(`---- ---- check server ---- ----`);
                console.log(server);
                if (api) {
                    this.updatePrinterList();
                } else {
                    this.printers[0].name = "未检测到打印插件";
                }
            },
        });
    },
    methods: {
        onFileDragEnter(e) {
            e.stopPropagation();
            e.preventDefault();
            if (e.dataTransfer) {
                e.dataTransfer.dropEffect = "copy";
            }
        },
        onFileDragDrop(e) {
            e.stopPropagation();
            e.preventDefault();
            const file = (e.dataTransfer?.files || [])[0];
            if (file) {
                const fileName = file.name || "";
                // const fileName = "";
                const pos = fileName.lastIndexOf(".");
                const ext = pos > 0 ? fileName.substring(pos + 1) : "";
                this.loadFileContent(file, (content) => {
                    if (ext.toLowerCase() === "json") {
                        this.printJsonContent(content);
                    } else if (ext.toLowerCase() === "wdfx") {
                        this.printWdfxContent(content);
                    }
                });
            }
        },
        onPrinterChanged() {
            console.log(`---- onPrinterChanged:`);
            console.log(this.currPrinter);
            if (this.currPrinter) {
                if (this.currPrinter.deviceDPI) {
                    this.printerDPI = this.currPrinter.deviceDPI;
                }
                if (this.currPrinter.deviceWidth) {
                    this.printerWidth = this.currPrinter.deviceWidth;
                }
            }
        },
        /**
         * @param {(files: File[]) => void} callback
         * @param {string} type
         */
        pickerFiles(callback, type) {
            if (type) this.pickerAccept = type;
            // 更新type后，accept不会立马生效
            setTimeout(() => {
                /**
                 * @type {HTMLInputElement}
                 */
                const ele = document.getElementById("file-picker");
                ele.onchange = (event) => {
                    const files = event.target.files;
                    if (files && files.length > 0) {
                        callback && callback(files);
                        ele.value = "";
                    }
                };
                ele.click();
            });
        },
        getJobAction() {
            return this.currAction;
        },
        getJobName() {
            if ((this.currAction & LPA_PrintActions.PrevBase64) !== 0) {
                // 该名称的打印任务不参与打印，仅用于返回白色底色的预览图片
                return "#!#Preview#!#";
            } else if ((this.currAction & LPA_PrintActions.Transparent) != 0) {
                // 该名称的打印任务不参与打印，进用于返回透明底色的预览图片
                return "#!#Transparent#!#";
            } else {
                // 打印任务名称，随便挑，只要不是"#!#"开头的名称都可以。
                return "jobName";
            }
        },
        getPrinterDpi() {
            return this.currAction === LPA_PrintActions.PrintData ? this.printerDPI : undefined;
        },
        getPrinterWidth() {
            return this.currAction === LPA_PrintActions.PrintData ? this.printerWidth : undefined;
        },
        /**
         * 更新打印机列表。
         */
        updatePrinterList() {
            if (!this.api) return;
            //
            const api = this.api;
            //
            api.getPrinters((values) => {
                // 清空旧打印机列表
                this.printers.splice(0);
                //
                if (values?.length > 0) {
                    for (const item of values) {
                        const title = api.isLocalPrinter(item)
                            ? item.deviceName || item.name
                            : `${item.deviceName || item.name}@${item.ip}`;
                        this.printers.push({
                            name: title,
                            value: item,
                        });
                    }
                } else {
                    this.printers.push({ name: "未检测到打印机", value: "" });
                }
                //
                this.currPrinter = this.printers[0].value;
                //
                this.onPrinterChanged();
            });
        },
        /**
         * 打开打印机测试
         */
        onOpenPrinter() {
            const printer = this.currPrinter || this.printers[0].value;
            this.api?.openPrinter(printer, (value) => {
                alert(value ? "打印机打开成功!" : "打印机打开失败");
            });
        },
        /**
         * 关闭打印机测试
         */
        onClosePrinter() {
            this.api.closePrinter();
        },
        /**
         * 获取打印机名称
         */
        onGetPrinterName() {
            if (this.api.isPrinterOpened()) {
                const name = this.api.getPrinterName();
                alert(name);
            } else {
                alert("打印机未打开");
            }
        },
        /**
         * 检测打印机是否打开
         */
        onIsPrinterOpened() {
            const value = this.api.isPrinterOpened();
            alert(value);
        },
        /**
         * 显示打印机首选项/属性
         */
        onShowPrinterProperty() {
            // 打印机首选项与打印机属性交替显示。
            this.api.showProperty({ showDocument: this.showDocument });
            // 切换下次的显示状态。
            this.showDocument = !this.showDocument;
        },
        /**
         * 直线绘制测试
         */
        onDrawLine() {
            const width = 45;
            const lineSpace = 5;
            const height = lineSpace * 4;
            const lineWidth = 0.5;
            //
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    //
                    this.api.drawLine({ x1: 0, y1: 5, x2: 45, lineWidth });
                    this.api.drawLine({ x1: 0, y1: 10, x2: 45, lineWidth, dashLens: [0.5, 0.5] });
                    this.api.drawLine({ x1: 0, y1: 15, x2: 45, lineWidth, dashLens: [0.7, 0.3] });
                    // 提交打印任务；
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 矢量图-绘制矩形测试
         */
        onDrawRect() {
            const width = 45;
            const height = 30;
            const padding = 2;
            // 创建打印任务
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    //
                    this.api.startPage();
                    // 第一页，打印矩形框
                    this.api.drawRectangle({
                        x: 0,
                        y: 0,
                        width: width,
                        height: height,
                        lineWidth: 0.4,
                    });
                    // 打印填充矩形
                    this.api.drawRectangle({
                        x: padding,
                        y: padding,
                        width: width - padding * 2,
                        height: height - padding * 2,
                        fill: true,
                    });
                    this.api.endPage();
                    // 第二页，打印圆角矩形框
                    this.api.startPage();
                    // 绘制圆角矩形框
                    this.api.drawRoundRectangle({
                        width: width,
                        height: height,
                        cornerWidth: 3,
                        lineWidth: 0.4,
                    });
                    // 绘制填充圆角矩形
                    this.api.drawRoundRectangle({
                        x: padding,
                        y: padding,
                        width: width - padding * 2,
                        height: height - padding * 2,
                        cornerWidth: 3,
                        fill: true,
                    });
                    this.api.endPage();
                    // 提交打印任务
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 矢量图-椭圆绘制测试
         */
        onDrawEllipse() {
            const width = 45;
            const height = 30;
            const padding = 2;
            // 创建打印任务。
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    //
                    // 绘制椭圆边框
                    this.api.drawEllipse({
                        x: 0,
                        y: 0,
                        width: width,
                        height: height,
                        lineWidth: 0.4,
                    });
                    // 绘制填充椭圆
                    this.api.drawEllipse({
                        x: padding,
                        y: padding,
                        width: width - padding * 2,
                        height: height - padding * 2,
                        fill: true,
                    });
                    // 提交打印任务。
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 矢量图-椭圆绘制测试
         */
        onDrawCircle() {
            const width = 30;
            const height = 30;
            const padding = 2;
            const radius = width * 0.5;
            // 创建打印任务。
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    //
                    // 绘制椭圆边框
                    this.api.drawCircle({ x: width * 0.5, y: height * 0.5, radius: radius, lineWidth: 0.4 });
                    // 绘制填充圆行
                    this.api.drawCircle({
                        x: width * 0.5,
                        y: height * 0.5,
                        radius: radius - padding,
                        fill: true,
                    });
                    // 提交打印任务。
                    this.api.commitJob((res) => {
                        //
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 字符串绘制测试
         */
        onDrawText() {
            const width = 40;
            const height = 30;
            const itemHeight = height / 4;
            const fontHeight = 4;
            const text = "上海道臻信息技术有限公司，www.detonger.com";
            let posY = 0;
            // 创建指定大小的打印任务，单位毫米
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    // 绘制第一条字符串，默认位置为(0, 0)
                    this.api.drawText({ text: text, fontHeight: fontHeight });
                    // 分割线
                    posY += itemHeight;
                    this.api.drawLine({ x1: 0, y1: posY, x2: width, y2: posY, lineWidth: 0.3 });

                    // 绘制第二条字符串，通过指定宽度来进行自动换行
                    this.api.drawText({ text: text, x: 0, y: posY, width: width, fontHeight: fontHeight });
                    // 分割线
                    posY += itemHeight;
                    this.api.drawLine({ x1: 0, y1: posY, x2: width, y2: posY, lineWidth: 0.3 });

                    // 绘制第三条字符串，同时指定宽高后，如果给定的区域显示不下，则进行字体自动缩小处理。
                    this.api.drawText({
                        text: text,
                        x: 0,
                        y: posY,
                        width: width,
                        height: itemHeight,
                        fontHeight: fontHeight,
                    });
                    // 分割线
                    posY += itemHeight;
                    this.api.drawLine({ x1: 0, y1: posY, x2: width, y2: posY, lineWidth: 0.3 });

                    // 绘制第四条字符串，可以通过指定 autoReturn，强制设置单行压缩模式；
                    this.api.drawText({
                        text: text,
                        x: 0,
                        y: posY,
                        width: width,
                        fontHeight: fontHeight,
                        autoReturn: 0,
                    });
                    // 提交打印任务，开始打印
                    this.api.commitJob((res) => {
                        //
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 一维码绘制测试
         */
        onDrawBarcode() {
            const width = 45;
            const height = 30;
            const text = "1234567890";
            const margin = 5;
            // 创建指定大小的打印任务，单位毫米
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    // 绘制外边框
                    this.api.drawRectangle({ width: width, height: height, lineWidth: 0.4 });
                    // 绘制一维码
                    this.api.draw1DBarcode({
                        text,
                        x: margin,
                        y: margin,
                        width: width - margin * 2,
                        height: height - margin * 2,
                        textHeight: 3,
                        textAlignment: 3,
                        horizontalAlignment: 1,
                        // barcodeType: 22,
                    });
                    // 提交打印任务，开始打印
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 二维码绘制测试
         */
        onDrawQrcode(data, callback) {
            const width = 40;
            const height = 30;
            const textHeight = 4;
            const margin = 2;
            const qrcodeWidth = height - margin * 2 - textHeight;
            const text = typeof data === "string" ? data : "上海道臻信息技术有限公司";
            // const text = "www.dothantech.com";
            // 创建指定大小的打印任务，单位毫米；
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    // 绘制外边框
                    this.api.drawRectangle({ width: width, height: height, lineWidth: 0.4 });
                    // 绘制二维码
                    this.api.draw2DQRCode({
                        text: text,
                        x: (width - qrcodeWidth) * 0.5,
                        y: margin,
                        width: qrcodeWidth,
                    });
                    // 绘制二维码下面的描述字符串
                    this.api.drawText({
                        text: text,
                        x: 0,
                        y: margin + qrcodeWidth,
                        width: width,
                        height: textHeight,
                        fontHeight: 3.5,
                        horizontalAlignment: 1,
                    });
                    // 提交打印任务，开始打印
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                        // 打印完毕后，执行回调，告诉调用者已经打印完毕。
                        callback && callback(true);
                    });
                },
            });
        },
        /**
         * PDF417绘制测试
         */
        onDrawPDF417() {
            const width = 45;
            const height = 30;
            const text = "上海道臻信息技术有限公司";
            // const text = "www.dothantech.com";
            const margin = 2;
            const textHeight = 4;
            // 创建指定大小的打印任务，单位毫米
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    // 绘制外边框
                    this.api.drawRectangle({ width: width, height: height, lineWidth: 0.4 });
                    // 绘制PDF417二维码
                    this.api.draw2DPdf417({
                        text: text,
                        x: margin,
                        y: margin,
                        width: width - margin * 2,
                        height: height - textHeight - margin * 2,
                    });
                    // 绘制二维码描述字符串
                    this.api.drawText({
                        text: text,
                        x: 0,
                        y: height - margin - textHeight,
                        width: width,
                        height: textHeight,
                        fontHeight: 3.4,
                        horizontalAlignment: 1,
                    });
                    // 提交打印任务，开始打印
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * DataMatrix绘制测试
         */
        onDrawDataMatrix() {
            const width = 40;
            const height = 30;
            // const text = "上海道臻信息技术有限公司";
            const text = "www.dothantech.com";
            const margin = 2;
            const textHeight = 4;
            const codeWidth = height - margin * 2 - textHeight;
            // 创建指定大小的打印任务，单位毫米
            this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    // 绘制外边框
                    this.api.drawRectangle({ width: width, height: height, lineWidth: 0.4 });
                    // 绘制DataMatrix二维码
                    this.api.draw2DDataMatrix({
                        text,
                        x: (width - codeWidth) * 0.5,
                        y: margin,
                        width: codeWidth,
                        height: codeWidth,
                    });
                    // 绘制二维码描述字符串
                    this.api.drawText({
                        text: text,
                        x: 0,
                        y: margin + codeWidth,
                        width: width,
                        height: textHeight,
                        fontHeight: 3.5,
                        horizontalAlignment: 1,
                    });
                    // 提交打印任务，开始打印
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 绘制图片URL测试
         */
        onDrawImageFile() {
            const width = 45;
            const height = 45;
            const margin = 5;
            // 创建指定大小的打印任务，单位毫米
            this.api.startPrintJob({
                width,
                height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printer: this.currPrinter,
                action: this.getJobAction(),
                callback: (success) => {
                    if (!success) return;
                    // 绘制图片内容
                    this.api.drawImage({
                        imageFile: "http://www.detonger.com/img/QRCode_OfficialAccounts.png",
                        x: margin,
                        y: margin,
                        width: width - margin * 2,
                        height: height - margin * 2,
                    });
                    // 提交打印任务，开始打印
                    this.api.commitJob((res) => {
                        // 如果当前任务类型为预览类型，则显示预览效果
                        this.previewJobs(res);
                    });
                },
            });
        },
        /**
         * 绘制BASE64图片测试
         */
        onDrawImageData() {
            const labelWidth = 30;
            const labelHeight = 30;
            const margin = 1;
            const url = "http://www.detonger.com/img/QRCode_OfficialAccounts.png";
            this.api.imageSrc2DataUrl(url, (dataUrl) => {
                // 创建指定大小的打印任务
                this.api.startPrintJob({
                    width: labelWidth,
                    height: labelHeight,
                    orientation: this.currOrientation,
                    jobName: this.getJobName(),
                    printer: this.currPrinter,
                    action: this.getJobAction(),
                    callback: (success) => {
                        if (!success) return;
                        // 绘制图片内容
                        this.api.drawImageD({
                            data: dataUrl,
                            x: margin,
                            y: margin,
                            width: labelWidth - margin * 2,
                            height: labelHeight - margin * 2,
                        });
                        // 提交打印任务，开始打印
                        this.api.commitJob((res) => {
                            // 如果当前任务类型为预览类型，则显示预览效果
                            this.previewJobs(res);
                        });
                    },
                });
            });
        },
        /**
         * 设置内容的对其方式测试
         */
        onSetAlign() {
            const width = 45;
            const height = 30;
            const itemWidth = width * 0.5;
            const itemHeight = height * 0.5;
            const fontHeight = 3.5;
            const lineWidth = 0.4;
            const text = "@上海道臻信息技术有限公司#";
            // const text = "www.dothantech.com";
            // 创建指定大小的打印任务，单位毫米
            const success = this.api.startPrintJob({
                width,
                height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printerName: this.currPrinter.name,
                action: this.getJobAction(),
                printerDPI: this.getPrinterDpi(),
                printerWidth: this.getPrinterWidth(),
            });
            if (!success) return;
            // 绘制辅助边框
            this.api.drawRectangle({ width: width, height: height, lineWidth: lineWidth });
            this.api.drawLine({
                x1: 0,
                y1: itemHeight,
                x2: width,
                y2: itemHeight,
                lineWidth: lineWidth,
            });
            this.api.drawLine({
                x1: itemWidth,
                y1: 0,
                x2: itemWidth,
                y2: height,
                lineWidth: lineWidth,
            });
            // 居左，常规字体；
            this.api.drawText({
                text: text,
                x: 0,
                y: 0,
                width: itemWidth,
                height: itemHeight,
                fontHeight: fontHeight,
                horizontalAlignment: 0,
                verticalAlignment: 0,
            });
            this.api.drawText({
                text: text,
                x: itemWidth,
                y: 0,
                width: itemWidth,
                height: itemHeight,
                fontHeight: fontHeight,
                fontStyle: 1,
                horizontalAlignment: 1,
                verticalAlignment: 1,
            });
            this.api.drawText({
                text: text,
                x: itemWidth,
                y: itemHeight,
                width: itemWidth,
                height: itemHeight,
                fontHeight: fontHeight,
                fontStyle: 2,
                horizontalAlignment: 2,
                verticalAlignment: 2,
            });
            this.api.drawText({
                text: text,
                x: 0,
                y: itemHeight,
                width: itemWidth,
                height: itemHeight,
                fontHeight: fontHeight,
                fontStyle: 2,
                horizontalAlignment: 3,
                verticalAlignment: 3,
            });
            this.api.commitJob({
                gapType: this.currGapType,
                printDarkness: this.currDarkness,
                printSpeed: this.currSpeed,
                callback: (res) => {
                    // 如果当前任务类型为预览类型，则显示预览效果
                    this.previewJobs(res);
                },
            });
        },
        /**
         * 设置内容的旋转测试。
         */
        onSetRotation() {
            const width = 45;
            const height = 30;
            const lineWidth = 0.35;
            const text = "上海道臻信息技术有限公司";
            const fontHeight = 3.5;
            const halfWidth = width * 0.5;
            const halfHeight = height * 0.5;
            //
            const success = this.api.startPrintJob({
                width: width,
                height: height,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printerName: this.currPrinter.name,
                action: this.getJobAction(),
                printerDPI: this.getPrinterDpi(),
                printerWidth: this.getPrinterWidth(),
            });
            if (!success) return false;
            // 将整张标签分割成四个区域，分别设置不同的旋转
            this.api.drawRectangle({ width, height, lineWidth });
            this.api.drawLine({ x1: 0, y1: halfHeight, x2: width, y2: halfHeight, lineWidth });
            this.api.drawLine({ x1: halfWidth, y1: 0, x2: halfWidth, y2: height, lineWidth });
            // 左上角内容不进行旋转
            this.api.drawText({
                text,
                x: 0,
                y: 0,
                width: halfWidth,
                height: halfHeight,
                fontHeight,
                orientation: 0,
            });
            // 右上角内容，右转90度
            this.api.drawText({
                text,
                x: halfWidth,
                y: 0,
                width: halfWidth,
                height: halfHeight,
                fontHeight,
                orientation: 90,
            });
            // 左下角内容，180度旋转
            this.api.drawText({
                text,
                x: halfWidth,
                y: halfHeight,
                width: halfWidth,
                height: halfHeight,
                fontHeight,
                orientation: 180,
            });
            // 右下角内容，270度旋转
            this.api.drawText({
                text,
                x: 0,
                y: halfHeight,
                width: halfWidth,
                height: halfHeight,
                fontHeight,
                orientation: 270,
            });
            //
            this.api.commitJob({
                gapType: this.currGapType,
                printDarkness: this.currDarkness,
                printSpeed: this.currSpeed,
                callback: (res) => {
                    // 如果当前任务类型为预览类型，则显示预览效果
                    this.previewJobs(res);
                },
            });
        },
        /**
         * 直接打印BASE64图片测试
         */
        onPrintImageData() {
            /**
             * @type {HTMLElement}
             */
            const datas = this.$refs["preview-list"];
            if (datas && datas.childNodes) {
                const childNodes = datas.childNodes;
                for (let i = 0; i < childNodes.length; i++) {
                    if (childNodes[i].src) {
                        this.api.printImage({
                            data: childNodes[i].src,
                            printerName: this.currPrinter?.name,
                            copies: 2,
                            orientation: this.currOrientation,
                        });
                    }
                }
            }
        },
        printRawData(rawData, callback) {
            const printer = this.currPrinter || {};
            return this.api.printRawData({
                // 打印数据，支持 Uint8Array，base64字符串，16进制字符串等格式的数据。
                data: rawData,
                // 打印机名称
                printerName: printer.name,
                // 打印份数
                // copies: 1,
                // 打印任务名称
                // jobName: "",
                callback: (res) => {
                    callback && callback(res);
                },
            });
        },
        /**
         * 循环打印所有打印数据。
         * @param {string[]} dataList 打印数据列表。
         * @param {number} index 当前打印页索引。
         */
        printRawList(dataList, index) {
            index = index || 0;
            if (!dataList || dataList.length <= 0) {
                console.log("未检测到打印数据！");
                return;
            }
            //
            var printData = dataList[index];
            if (!printData) {
                console.log("---- 无效的打印数据！");
                return;
            }
            //
            console.log(`----- 准备打印第 [${index + 1}] 条数据:`);
            this.printRawData(printData, (res) => {
                if (res) {
                    console.log(`---- 第 [${index + 1}] 条数据打印成功！`);
                } else {
                    console.log(`---- 第 [${index + 1}] 条数据打印失败！`);
                }
                //
                if (++index < dataList.length) {
                    // 打印下一张标签
                    this.printRawList(dataList, index);
                } else {
                    console.log("---- 所有标签全部打印完毕！");
                }
            });
        },
        onPrintRawData() {
            if (!this.printData || this.printData.length <= 0) {
                console.warn(`---- 未检测到打印数据！`);
                return;
            }
            const pageList = this.printData.map((v) => v.join(""));
            this.printRawList(pageList, 0);
        },
        /**
         * 表格打印测试。
         */
        onTablePrintTest() {
            const api = this.api;
            const labelWidth = 70;
            const labelHeight = 50;
            const res = api.startPrintJob({
                width: labelWidth,
                height: labelHeight,
                orientation: this.currOrientation,
                jobName: this.getJobName(),
                printerName: this.currPrinter.name,
                action: this.getJobAction(),
                printerDPI: this.getPrinterDpi(),
                printerWidth: this.getPrinterWidth(),
            });
            if (!res) {
                // 打印机链接失败，或者打印任务创建失败
                return;
            }
            // 标题
            api.drawText({
                text: "7天连锁酒店",
                x: 3,
                y: 3,
                fontHeight: 6.35,
            });
            api.drawText({
                text: "固定资产标牌",
                x: 41,
                y: 5,
                fontHeight: 3.7,
            });
            //
            api.drawTable({
                x: 2,
                y: 10,
                width: labelWidth - 4,
                height: labelHeight - 12,
                columnCount: 3,
                rowCount: 6,
                lineWidth: 0.3,
                // 0表示自适应
                columnWidths: [0, 18, 15],
                fontHeight: 3.7,
                horizontalAlignment: 0,
                tableRows: [
                    [
                        {
                            text: "资产编号：7hotel-js012",
                            columnSpan: 3,
                        },
                    ],
                    [
                        {
                            text: "资产名称：IBM大型机",
                            columnSpan: 3,
                        },
                    ],
                    [
                        { text: "使用部门：技术部" },
                        {
                            text: "规格型号：ES900",
                            columnSpan: 2,
                        },
                    ],
                    [
                        { text: "所在地点：配电房" },
                        {
                            text: "启用日期：2017/09",
                            columnSpan: 2,
                        },
                    ],
                    [
                        {
                            text: "备注：保质三年",
                            columnSpan: 2,
                        },
                        "",
                        {
                            type: "qrcode",
                            text: "[qrcode]",
                            rowSpan: 2,
                            horizontalAlignment: 1,
                            margin: 0.5,
                        },
                    ],
                    [
                        {
                            type: "barcode",
                            text: "[barcode]",
                            columnSpan: 2,
                            margin: 0.5,
                        },
                    ],
                ],
            });
            this.api.commitJob({
                gapType: this.currGapType,
                jobArguments: [
                    [
                        { k: "barcode", v: "100000001" },
                        { k: "qrcode", v: "200000001" },
                    ],
                ],
                callback: (res) => {
                    // 如果当前任务类型为预览类型，则显示预览效果
                    this.previewJobs(res);
                },
            });
        },
        /**
         * 打印JSON格式绘制任务。
         */
        onJsonPrintTest() {
            const api = this.api;
            const printer = this.currPrinter || {};
            const labelWidth = 40;
            const labelHeight = 30;
            // var url = 'http://www.detonger.com/img/QRCode_OfficialAccounts.png';
            // var text1 = "上海道臻信息技术有限公司";
            // var text2 = '1234567';
            // var text1 = "[数据1]"; // 通过外部数据源模式进行打印的时候，通过中括号来选择关键字。
            //
            api.print({
                action: this.getJobAction(),
                printerInfo: {
                    printerName: printer.name,
                },
                jobInfo: {
                    jobWidth: labelWidth,
                    jobHeight: labelHeight,
                    orientation: this.currOrientation,
                    gapType: this.currGapType,
                },
                jobPages: [
                    // 第一张标签，外边框里面套个二维码
                    [
                        { type: "rectangle", width: labelWidth, height: labelHeight, lineWidth: 0.4 },
                        // { type: 'roundRectangle', width: labelWidth, height: labelHeight, lineWidth: 0.4, cornerWidth: 2 },
                        // { type: "text", text: text1, width: labelWidth, height: labelHeight, fontHeight: 4 },
                        {
                            type: "barcode",
                            text: "[barcode]",
                            x: 5,
                            y: 5,
                            width: 30,
                            height: 20,
                            textHeight: 4,
                            textAlignment: 3,
                        },
                        // { type: 'qrcode', text: [qrcode], x: 10, y: 5, width: 20, eccLevel: 1 },
                        // { type: 'pdf417', text: text2, x: 5, y: 5, width: 30, height: 20 },
                        // // 绘制图片url
                        // { type: 'image', imageFile: url, x: 10, y: 5, width: 20, height: 20 },
                        // // 绘制BASE64字符串
                        // { type: 'image', imageFile: imgSrc, x: 10, y: 5, width: 20, height: 20 },
                        // { type: 'line', x1: 0, y1: 5, x2: labelWidth, y2: 5, lineWidth: 0.4 },
                        // { type: 'dashLine', x1: 0, y1: 10, x2: labelWidth, y2: 10, lineWidth: 0.4, dashLen: '1,0.5' },
                    ],
                ],
                jobArguments: [
                    {
                        barcode: "10000001",
                        qrcode: "二维码测试1",
                    },
                    {
                        barcode: "10000002",
                        qrcode: "二维码测试2",
                    },
                ],
                callback: (results) => {
                    // 显示预览效果
                    if (results) {
                        this.previewJobs(results);
                    }
                },
            });
        },
        printJsonContent(content) {
            const api = this.api;
            const printAction = this.getJobAction();
            api.print({
                action: printAction,
                printerInfo: {
                    printerName: this.currPrinter ? this.currPrinter.name : undefined,
                },
                jobInfo: { orientation: this.currOrientation },
                content: content,
                // jobArguments: [
                //     [
                //         { k: "数据1", v: "" },
                //         { k: "数据2", v: "" },
                //     ],
                // ],
                callback: (results) => {
                    // 显示预览效果
                    if (printAction !== 0x1000 && results) {
                        this.previewJobs(results);
                    }
                },
            });
        },
        onWdfxPrintTest() {
            this.pickerFiles((files) => {
                if (files && files.length > 0) {
                    this.loadFileContent(files[0], (content) => {
                        if (content) {
                            this.printWdfxContent(content);
                        }
                    });
                }
            }, ".wdfx");
        },
        printWdfxContent(content) {
            const printerName = this.currPrinter ? this.currPrinter.name : undefined;
            const printAction = this.getJobAction();
            const api = this.api;
            //
            api.printWdfx({
                action: printAction,
                printerInfo: {
                    printerName: printerName,
                },
                jobInfo: { orientation: this.currOrientation },
                content: content,
                // jobArguments: [
                //     [
                //         { k: "数据1", v: "" },
                //         { k: "数据2", v: "" },
                //     ],
                // ],
                callback: (results) => {
                    // 显示预览效果
                    if (printAction !== 0x1000 && results) {
                        this.previewJobs(results);
                    }
                },
            });
        },
        loadFileContent(file, onComplete) {
            if (file) {
                const reader = new FileReader();
                reader.onload = () => {
                    onComplete && onComplete(reader.result);
                };
                reader.readAsText(file);
            }
        },
        addPreview(data) {
            if (!data) return;
            const previewGroup = this.$refs["preview-list"];
            const img = document.createElement("img");
            img.src = data;
            previewGroup.appendChild(img);
            // 换行
            previewGroup.appendChild(document.createElement("br"));
        },
        /**
         * 获取当前任务的图片信息；
         */
        previewJobs(res) {
            if (!res) return;
            // 先清空预览区域；
            this.$refs["preview-list"].innerHTML = "";
            //
            if (res.printData) {
                this.printData = res.printData;
                console.log(`---- printData:`);
                console.log(res.printData);
            }
            if (res.previewData) {
                this.previewPages(res.previewData);
            }
        },
        previewPages(pages) {
            if (pages && pages.length > 0) {
                for (const page of pages) {
                    this.addPreview(page);
                }
            }
        },
        /**
         * 获取 #preview-list中所有img的src；
         */
        getPreviewList() {
            const previewGroup = this.$refs["preview-list"];
            const pageList = [];
            for (let i = 0; i < previewGroup.children.length; i++) {
                const imgElement = previewGroup.children[i];
                if (imgElement?.src) pageList.push(imgElement.src);
            }
            return pageList;
        },
        pix2mm(pxValue, printDpi) {
            printDpi = printDpi || 203;
            return (pxValue * 25.4) / printDpi;
        },
    },
};
</script>

<style lange="css" scoped>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
}
body {
    text-align: center;
}
.dz-title {
    font-weight: bold;
    font-size: 20px;
}
.dz-opt-group .dz-opt-item {
    display: flex;
    width: 400px;
    height: 28px;
    margin: 0 auto 10px auto;
}
.dz-opt-group .dz-opt-item .dz-opt-item-title {
    flex: 2;
    display: inline-block;
    text-align: right;
    background-color: lightblue;
    margin: 5px;
    padding: 5px;
}
.dz-opt-group .dz-opt-item .dz-opt-item-value {
    flex: 5;
    background-color: lightyellow;
    max-width: 280px;
}
fieldset {
    width: 600px;
    margin: auto;
    min-height: 50px;
}
a {
    color: #42b983;
    cursor: pointer;
}
a.button {
    cursor: pointer;
    padding: 0.4em 2em;
    margin: 0.25em 0.5em;
    border-radius: 0.5em;
    display: inline-block;
    transition: all 0.15s ease;
    box-sizing: border-box;
    border: 1px solid #4fc08d;
}
.dz-btn-group {
    text-align: center;
    margin: 0;
}
.dz-btn-group a {
    display: inline-block;
    width: 250px;
    margin: 10px 5px 0 5px;
}
.dz-preview-group {
    background-color: lightgoldenrodyellow;
    min-height: 100px;
}
</style>
